package corp.edu.amadeus.core.business.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import org.apache.log4j.Logger;
import corp.edu.amadeus.core.business.service.ifc.IMultimediaStorageService;
import corp.edu.amadeus.utils.file.FileUtils;

public class MultimediaStorageServiceImpl implements IMultimediaStorageService {

	private String baseFolder = "";
	private static Logger log = Logger.getLogger(MultimediaStorageServiceImpl.class);

	public MultimediaStorageServiceImpl(String multimedia_repo_property)
		throws Exception {
		String base = System.getProperty(multimedia_repo_property);
		this.checkBase(base);
		this.baseFolder = base;
	}

	private void checkBase(String base)
		throws Exception {
		File base_folder = new File(base);
		if(base_folder.exists()) {
			if(!base_folder.isDirectory()) {
				throw new Exception("El base " +
						base + " NO es un directorio.");
			}
			if(!base_folder.canWrite()) {
				throw new Exception("No se permite "
						+ " escribir en la ruta: " + base);
			}
		} else {
			if(!base_folder.mkdirs()) {
				throw new Exception("No se puede crear el "
						+ "base en la ruta: " + base);
			}
		}
	}

	public String getBaseFolder() {
		return this.baseFolder;
	}

	public void addFile(File file, String filename)
		throws Exception {
		byte[] file_content = FileUtils.extractFileContent(file);
		String absPath = this.baseFolder + File.separator + filename;
		File targetFile = new File(absPath);
		FileOutputStream fos = new FileOutputStream(targetFile);
		FileUtils.binaryTransferm(fos, file_content);
	}

	public boolean deleteFile(String filename) {
		String absPath = this.baseFolder + File.separator + filename;
		File targetFile = new File(absPath);
		if(targetFile.exists()) {
			return targetFile.delete();
		}
		return false;
	}
}